package com.winner.mongodb.controller;

import com.mongodb.client.result.DeleteResult;
import com.winner.mongodb.controller.base.BaseController;
import com.winner.mongodb.model.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.util.List;

@Slf4j
@RestController
@Validated
@RequestMapping(value = "/user")
public class UserController extends BaseController {

    @Autowired
    private MongoTemplate mongoTemplate;

//    localhost:8080/user
//    {
//        "name": "sino",
//         "age": 18,
//           "createTime": "2021-11-27 03:00:02:002"
//    }
    @PostMapping
    public Object save(@Validated @RequestBody User user) {
        mongoTemplate.save(user); //默认不支持级联保存
        return success(user);
    }

    @DeleteMapping("/{id}")
    public Object delete(@PathVariable("id") String id) {
        Query query = Query.query(Criteria.where("id").is(id));
        DeleteResult remove = mongoTemplate.remove(query, User.class); // 第二个参数表示collectionName或User.class 都可以
        return success(remove);
    }

    //   localhost:8080/user/:id
    @GetMapping("/{id}")
    public Object get(@PathVariable("id") String id) {
        User user = mongoTemplate.findById(id, User.class);
        return success(user);
    }


//is相当于等于
//in相当于sql中的in
//ne相当于不等于
//orOperator接受多个条件，组成or逻辑
// Criteria.where("age").gte(age).andOperator(Criteria.where("name").is("sino").orOperator(Criteria.where("name").is("sino"));

    /**
     * 分页查询
     * localhost:8080/user/list/10/1/0
     * @Validated @NotEmpty(message = "age can not be empty")
     *
     * @Param("age") @Validated @NotEmpty(message = "age不能为空")   ,defaultvalue=0
     *
     * @param pageSize
     * @param pageNo
     * @param age
     */
    @GetMapping("/list/{pageSize}/{pageNo}")
    public Object list(@PathVariable  Integer pageSize,
                       @PathVariable Integer pageNo,
                       @NotNull(message = "age can not be empty") Integer age) {

        Query query = new Query();
        Criteria criteria = Criteria.where("age").gte(age); // 传递多个查询条件
        query.addCriteria(criteria);
        // springboot 2.2.1（含）以上的版本Sort已经不能再实例化了，构造方法已经是私有的了！  query.with(new Sort(Sort.Direction.DESC, "age")); 会报错,改用Sort.by(Sort.Direction.DESC, "age")
        query.with(Sort.by(Sort.Direction.DESC, "age"));
        PageRequest pageRequest = PageRequest.of(pageNo - 1, pageSize);
        query.with(pageRequest);
        Long total = mongoTemplate.count(query, User.class);
        List<User> list = mongoTemplate.find(query, User.class);
        PageImpl<User> page = new PageImpl(list, pageRequest, total);
        return success(page);

//        PageRequest pageRequest = PageRequest.of(pageNo - 1, pageSize, new Sort(Sort.Direction.ASC, "age"));
//        Page<User> page = userRepository.getUserByAgeGreaterThan(age, pageRequest);
//        return success(page);
    }

}
